<template>
  <div class="panel-header">
    <div class="panel-title">
      <i class="panel-icon alarm-icon"></i>
      <span>报警时间设备排名</span>
    </div>
  </div>
  <div class="panel-body">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
const chart = ref(null)

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chart.value = echarts.init(chartRef.value)

  // 设置图表响应式
  const resizeHandler = () => {
    chart.value && chart.value.resize()
  }
  window.addEventListener('resize', resizeHandler)

  // 组件卸载时移除事件监听
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler)
    chart.value && chart.value.dispose()
  })

  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chart.value) return

  // 模拟数据
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '报警时间(分钟)'
    },
    yAxis: {
      type: 'category',
      data: ['设备1', '设备2', '设备3', '设备4', '设备5'],
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: '报警时间',
        type: 'bar',
        data: [120, 90, 70, 50, 30],
        itemStyle: {
          color: function(params) {
            // 根据数值设置不同的颜色
            const value = params.value;
            if (value > 100) return '#F56C6C';
            if (value > 60) return '#E6A23C';
            return '#67C23A';
          }
        }
      }
    ]
  }

  chart.value.setOption(option)
}

onMounted(() => {
  initChart()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
